﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IRC.IRepairClouds.DataLayer
{
    public abstract class LazzyLoaderBase<T>
    {
        private T _value;
        private bool _isLoaded = false;

        public LazzyLoaderBase()
        {
        }

        public LazzyLoaderBase(T value)
        {
            _value = value;
            _isLoaded = true;
        }

        public bool IsLoaded
        {
            get { return _isLoaded; }
        }

        public T Value
        {
            get
            {
                if (!_isLoaded) {
                    _value = GetValue();
                    _isLoaded = true;
                }
                return _value;
            }
        }

        protected abstract T GetValue();

        public override string ToString()
        {
            return this.Value.ToString();
        }

        public static explicit operator T(LazzyLoaderBase<T> value)
        {
            return value.Value;
        }
    }


    public class LazzyLoader<T> : LazzyLoaderBase<T>
    {
        private Func<T> _getValue;

        public LazzyLoader(T value)
            : base(value)
        {
        }

        public LazzyLoader(Func<T> getValue)
        {
            _getValue = getValue;
        }

        protected override T GetValue()
        {
            return _getValue();
        }
    }

    public class LazzyLoader<T, TC> : LazzyLoaderBase<T>
    {
        private Func<TC, T> _getValue;
        private TC _context;

        public LazzyLoader(TC context, Func<TC, T> getValue)
        {
            _context = context;
            _getValue = getValue;
        }

        public TC Context
        {
            get { return _context; }
        }

        protected override T GetValue()
        {
            return _getValue(_context);
        }
    }
}
